package com.yft.data.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yft.data.FangYuanList;
import com.yft.data.User;
import com.yft.data.service.BlackListService;
import com.yft.data.service.DataService;
import com.yft.data.service.UserService;
import com.yft.data.util.StringUtil;

@Controller
@RequestMapping("data")
public class DataController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(DataController.class);
	
	@Autowired
	private DataService dataService;
	@Autowired
	private UserService userService;
	@Autowired
	private BlackListService blackListService;

	@RequestMapping(value = "getblacklist", method = RequestMethod.GET)
	@ResponseBody
	public List<String> getBlackList(HttpServletRequest request, HttpSession session)
	{
		return blackListService.getBlackList();
	}
	
	@RequestMapping(value = "setblacklist", method = RequestMethod.GET)
	@ResponseBody
	public int setBlackList(HttpServletRequest request, HttpSession session)
	{
		return dataService.setBlackList();
	}
	/**
	 * @param userid
	 * @param corpid
	 * @param pageno
	 * @param pagesize
	 * @param type
	 * @param cityid
	 * @param regionname
	 * @param search
	 * @param datetype
	 * @param pricetype
	 * @param areatype
	 * @param roomtype
	 * @param request
	 * @param session
	 * @return
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "fylist", method = RequestMethod.GET)
	@ResponseBody
	public FangYuanList getFYList(
			@RequestParam("userid") String userid,
			@RequestParam("corpid") Integer corpid,
			@RequestParam("pageNo") Integer pageno,
			@RequestParam("pageSize") Integer pagesize,
			@RequestParam(value = "type", required = false) Integer type,
			@RequestParam("cityid") Integer cityid,
			@RequestParam(value = "area", required = false) String area,
			@RequestParam(value = "search", required = false) String search,
			@RequestParam(value = "dateType", required = false) String datetype,
			@RequestParam(value = "priceType", required = false) String pricetype,
			@RequestParam(value = "spaceType", required = false) String spacetype,
			@RequestParam(value = "roomType", required = false) String roomtype,
			HttpServletRequest request,HttpServletResponse response, HttpSession session) {
		response.setContentType("text/html;charset=UTF-8");
		type = StringUtil.dealNull(type);
		area = StringUtil.dealNull(area);
		search = StringUtil.dealNull(search);
		datetype = StringUtil.dealNull(datetype);
		pricetype = StringUtil.dealNull(pricetype);
		spacetype = StringUtil.dealNull(spacetype);
		roomtype = StringUtil.dealNull(roomtype);
		try {
			area = new String(area.trim().getBytes("ISO-8859-1"), "utf-8");
			search = new String(search.trim().getBytes("ISO-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.debug("转码不成功", e);
		}
		FangYuanList fylist = new FangYuanList();
		try {
			if (userService.find(corpid, userid)&&blackListService.isNotExpire(corpid, userid)) {
				// 查询数据列表
				List<Map<String, Object>> list = dataService.getFanYuanList(
						pageno, pagesize, type, cityid, area, search,
						StringUtil.strToInt(datetype), StringUtil.strToInt(pricetype),
						StringUtil.strToInt(spacetype), StringUtil.strToInt(roomtype));
				if(blackListService.getBlackList(userid).size()>0)
				{
					//过滤用户黑名单的电话
					dealUserBlackList(userid, list);
				}
				int count = 500;
//				count = dataService.getCountMongo(type, cityid, area, search,
//						StringUtil.strToInt(datetype), StringUtil.strToInt(pricetype),
//						StringUtil.strToInt(spacetype), StringUtil.strToInt(roomtype));
				ObjectMapper objectMapper = new ObjectMapper();
				String str = null;
				try {
					str = objectMapper.writeValueAsString(list);
				} catch (JsonGenerationException e) {
					logger.error(e.getMessage());
				} catch (JsonMappingException e) {
					logger.error(e.getMessage());
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
				fylist.setList(str);
				fylist.setPageNo(pageno);
				fylist.setPageSize(pagesize);
				fylist.setPageCount((count / pagesize) + 1);
				fylist.setTotalCount(count);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return fylist;
		}

	}

	private void dealUserBlackList(String userid, List<Map<String, Object>> list) {
		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		List<String> blacklist = blackListService.getBlackList(userid);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			//公共黑名单过滤
			if(!blacklist.contains(map.get("phone"))&&!blacklist.contains(map.get("imgUrl")))
			{
				list2.add(map);
			}
		}
	}

	/**
	 * @param infoid
	 * @param corpid
	 * @param userid
	 * @param request
	 * @param session
	 * @return
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "fydetail", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getFYDetail(
			@RequestParam("infoid") Integer infoid,
			@RequestParam("corpid") Integer corpid,
			@RequestParam("userid") String userid, HttpServletRequest request,
			HttpSession session) {

		// logger.debug("fydetail"+corpid+":"+userid);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (blackListService.isNotExpire(corpid, userid)) {
				if (1 == dataService.updateReadCount(infoid)) {
					map = dataService.getFanYanDetail(infoid);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return map;
		}
	}

	/**
	 * 获得城市id表
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "getcity", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> getCity(HttpServletRequest request,
			HttpSession session) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		return list;
	}

	// -------------------------------------------------//
	// 测试内容
	// -------------------------------------------------//
	@RequestMapping("index")
	public String hello() {
		System.out.println("index/hello");
		return "index";
	}

	/**
	 * 测试返回JSON数据
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "test")
	@ResponseBody
	public List<User> test(HttpSession session) {
		User user = new User();
		user.setName("刘亚非");
		user.setPass("123456");
		user.setList("[test:321321]");
		List<User> list = new ArrayList<User>();
		list.add(user);
		User user2 = new User();
		user2.setName("test");
		user2.setPass("123");
		user2.setList("[test:132]");
		list.add(user2);
		return list;
	}

	/**
	 * 测试json2
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "test2")
	@ResponseBody
	public List<Map<String, Object>> test2(HttpSession session) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new ConcurrentHashMap<String, Object>();
		map.put("city", "北京");
		map.put("building", "保利大厦");
		list.add(map);
		Map<String, Object> map2 = new ConcurrentHashMap<String, Object>();
		map2.put("city", "上海");
		map2.put("building", "金茂大厦");
		list.add(map2);

		return list;
	}

	/**
	 * 测试json3
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "test3")
	@ResponseBody
	public User test3(HttpSession session) {
		// System.out.println("test3") ;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new ConcurrentHashMap<String, Object>();
		map.put("city", "北京");
		map.put("building", "保利大厦");
		list.add(map);
		Map<String, Object> map2 = new ConcurrentHashMap<String, Object>();
		map2.put("city", "上海");
		map2.put("building", "金茂大厦");
		ObjectMapper objectMapper = new ObjectMapper();
		String str = null;
		try {
			str = objectMapper.writeValueAsString(list);
		} catch (JsonGenerationException e) {
			logger.error(e.getMessage());
		} catch (JsonMappingException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		logger.debug("数据：" + str);
		list.add(map2);
		User user = new User();
		user.setName("刘亚非");
		user.setPass("123456");
		user.setList(str);
		return user;
	}
}
